<?php

namespace app\api\model\product;

use app\api\model\plus\discount\Product as DiscountProductModel;
use app\common\model\product\Category as CategoryModel;
use app\common\model\product\ProxyCategory;
use app\api\model\order\Order as OrderModel;
use app\common\model\product\Product as ProductModel;
use app\common\model\supplier\CategoryStatus as CategoryStatusModel;
use app\common\model\file\UploadFile as UploadFileModel;

/**
 * 商品分类模型
 */
class Category extends CategoryModel
{
    /**
     * 隐藏字段
     */
    protected $hidden = [
        'app_id',
        'update_time'
    ];

    // 获取指定分类 0非新人 1新人
    public function newcomer($type)
    {
        return $this->where('type', '=', $type)->column('category_id');
    }

    public function getProcuteList($parentId=0,$userInfo,$shop_supplier_id=0)
    {
        //首单数据
        $OrderModel = new OrderModel;
        $firstOrder = $OrderModel->getCount($userInfo, 'all',true);
        $firstYN = ($firstOrder>0)?1:0; //会员：2全部，1普通会员，0新人
        // 商品分类列表
        // $list = CategoryModel::getCacheTree($firstYN);
        $list = self::getSupplierCate([],$firstYN,$shop_supplier_id)['tree'];
        // if($city_id>0){
        //     foreach ($list as $k => $v){
        //         $list[$k]['child'] = self::getProxyCate($v['child'],$city_id);
        //     }
        // }
        // 二级分类
        $cateary = CategoryModel::smallNameList($parentId,$list);

        $outary = [];
        $discount_product_data = (new DiscountProductModel())->getDiscountAtivityProduct(); //限时优惠商品id
        foreach ($cateary as $key => $value) {
            $outary[$key]['category'] = $value;
            $param = [
                'list_rows'=>9999,
                'category_id'=>$value['category_id'],
                'sortType'=>'name'
            ];
            $data = (new ProductModel())->getListByUser($param, $userInfo, 1);
            $datalist = $data->toArray();
            foreach ($datalist as $k => $v){
                $v['discount_product_data'] = [];
                if(isset($discount_product_data[$v['product_id']]) && $discount_product_data[$v['product_id']]){
                    $v['discount_product_data'] = $discount_product_data[$v['product_id']];
                    $v['activity_type'] = 'discount'; //限时优惠
                }else{
                    $v['activity_type'] = 'putong'; //未参加活动的商品
                }

                $datalist[$k] = $v;

            }
            //如果没商品 页面空了 尽量缩小显示大小
            if(count($datalist)==0){
                $outary[$key]['category']['name'] = '';
            }
            $outary[$key]['list'] = $datalist;
        }
        return $outary;
    }

    public static  function getProxyCate($cateary,$city_id)
    {
        $ProxyCategory = new ProxyCategory();
        $map = [];
        $map[] = ['city_id','=',$city_id];
        $map[] = ['audit_status','=',1];
        $proxy_cate = $ProxyCategory -> where($map) -> select() -> toArray();

        $array = [];
        foreach ($proxy_cate as $key => $value){
            foreach ($cateary as $k => $v){
                if($value['category_id'] == $v['category_id']){
                    $v['name'] = $value['alias'];
                    $array[] = $v;
                }
            }
        }
        return $array;
    }

    /**
     * @Exp    商户分类
     * @Author Mr.Z
     * @param  [type]     $where            [description]
     * @param  integer    $newPeple         [会员：1普通会员，0新人]
     * @param  integer    $shop_supplier_id [description]
     * @return [type]                       [description]
     */
    public static function getSupplierCate($where,$newPeple=1,$shop_supplier_id=0)
    {
        $base = ['audit_status' => 1];
        if ($where) {
            $base = array_merge($base, $where);
        }
        $model = (new self)->where($base);

        $Cmodel = (new CategoryStatusModel())->alias('s')->where('s.shop_supplier_id','=',$shop_supplier_id)->join('category c','c.category_id=s.category_id');

        if($newPeple==1){
            $Cmodel = $Cmodel->where('c.type','=',0);
        }

        $Cmodel_a = $Cmodel_b = $Cmodel;
        // 20240513 Mr.Z调整为新增的不显示----where('s.show_status','=',1)
//        $cs_ids = $Cmodel_a->where('s.show_status','=',1)->column('s.category_id as category_id');

//        $bqsql = $Cmodel_b->where('s.show_status','=',1)->field('s.category_id as category_id,c.name as name,s.show_status as is_show,s.sort as sort,c.parent_id as parent_id,c.type as type,c.image_id as image_id')->buildSql();

        // $data = $model->alias('a')
        //     ->where('category_id','not in',$cs_ids)
        //     ->where(['a.is_show'=>1])
        //     ->order(['type'=>'desc','sort' => 'asc', 'category_id' => 'asc'])
        //     ->union($bqsql)
        //     ->field('category_id,name,is_show,sort,parent_id,type,image_id')
        //     ->withAttr('images', function ($value, $data) {
        //         return UploadFileModel::detail($data["image_id"]);
        //     })
        //     ->append(['images'])
        //     ->select();
        // 20240513 Mr.Z调整为新增的不显示
//        $data = $model->alias('a')
//            ->where('category_id','in',$cs_ids)
//            ->order(['type'=>'desc','sort' => 'asc', 'category_id' => 'asc'])
//            ->field('category_id,name,is_show,sort,parent_id,type,image_id')
//            ->withAttr('images', function ($value, $data) {
//                return UploadFileModel::detail($data["image_id"]);
//            })
//            ->append(['images'])
//            ->select();
        // 20240523 Mr.Z 调整不正确的地方
        $data = $Cmodel_b->where('s.show_status','=',1)
            ->field('s.category_id as category_id,c.name as name,s.show_status as is_show,s.sort as sort,c.parent_id as parent_id,c.type as type,c.image_id as image_id')
            ->withAttr('images', function ($value, $data) {
                return UploadFileModel::detail($data["image_id"]);
            })
            ->order('sort asc')
            ->append(['images'])
            ->select();

        $all = !empty($data) ? $data->toArray() : [];

        $tree = [];
        foreach ($all as $first) {
            if ($first['parent_id'] != 0) continue;
            $twoTree = [];
            foreach ($all as $two) {
                if ($two['parent_id'] != $first['category_id']) continue;
                $threeTree = [];
                foreach ($all as $three)
                    $three['parent_id'] == $two['category_id']
                    && $threeTree[$three['category_id']] = $three;
                !empty($threeTree) && $two['child'] = $threeTree;
                array_push($twoTree, $two);
            }
            if (!empty($twoTree)) {
                $temp_two_tree = array_column($twoTree, 'sort');
                array_multisort($temp_two_tree, SORT_ASC, $twoTree);
                $first['child'] = $twoTree;
            }
            array_push($tree, $first);
        }

        return compact('all', 'tree');
    }
}